package com.shijunhao.graduation.controller.system;


import com.shijunhao.graduation.annotations.OperationLog;
import com.shijunhao.graduation.domain.bean.ResultCode;
import com.shijunhao.graduation.domain.entity.OrgUser;
import com.shijunhao.graduation.properties.OperationTarget;
import com.shijunhao.graduation.properties.OperationType;
import com.shijunhao.graduation.service.system.IOrgUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author shijunhao
 * @since 2022-03-02
 */
@RestController
@RequestMapping("/org-user")
@Api(tags = "用户管理")
public class OrgUserController {
    @Autowired
    private IOrgUserService orgUserService;

    @GetMapping("/getById/{id}")
    @ApiOperation("根据id查找用户信息")
    public OrgUser getById(@PathVariable Long id) {
        return orgUserService.getById(id);
    }

    @PostMapping("/insert")
    @ApiOperation("插入用户数据")
    @OperationLog(target = OperationTarget.USER,type = OperationType.INSERT,description = "用户管理")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResultCode<Boolean> insert(@RequestBody List<OrgUser> users) {
        return ResultCode.success(orgUserService.insertBatch(users));
    }

    @PostMapping("/enable/{id}")
    @ApiOperation("启用用户")
    @OperationLog(target = OperationTarget.USER,type = OperationType.UPDATE,description = "启用禁用用户")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResultCode<Boolean> enable(@PathVariable Long id) {
        OrgUser user = orgUserService.getById(id);
        user.setEnable(!user.getEnable());
        orgUserService.updateById(user);
        String msg = user.getEnable() ? "启用成功" : "禁用成功";
        return ResultCode.success(msg);
    }

    @PostMapping("/role/{id}/{roleId}")
    @ApiOperation("更换角色")
    @OperationLog(target = OperationTarget.USER,type = OperationType.UPDATE,description = "修改角色")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResultCode<Boolean> enable(@PathVariable Long id, @PathVariable Integer roleId) {
        OrgUser user = orgUserService.getById(id);
        user.setRole(roleId);
        return ResultCode.success("更换成功",orgUserService.updateById(user));
    }


}
